'use strict';

const Controller = require('egg').Controller;
const BaseController = require('./base.js');
const fs = require('mz/fs');

class ProductController extends BaseController {
    async index() {
        let page=this.ctx.request.query.page?this.ctx.request.query.page:1;
        let pageSize=4;
        let result = await this.ctx.model.Product.findAll({
            include: { model: this.ctx.model.ProductCate },
            limit:pageSize,
            offset:(page-1)*pageSize
        });
        //获取总数量
        let total=await this.ctx.model.Product.count();

        await this.ctx.render("admin/product/index", {
            list: result,
            totalPages:Math.ceil(total/pageSize),
            page:page
        });

        //this.ctx.body = "菜品首页 请访问 product/add 实现图片上传 "
    }
    async add() {
        let result = await this.ctx.model.ProductCate.findAll();
        await this.ctx.render("admin/product/add", {
            cateList: result
        })
    }

    //单文件上传
    async doAdd() {
        const { ctx } = this;
        const body = ctx.request.body;
        const file = ctx.request.files[0];
        
        if (body.title == "") {
            await this.error("菜品名称不能为空", `/${this.config.adminPath}/product/add`);
            return;
        }
        if (body.price == "") {
            await this.error("菜品价格不能为空", `/${this.config.adminPath}/product/add`);
            return;
        }
        if (file) {
            var source = fs.createReadStream(file.filepath);
            var filename = this.ctx.service.tools.getCosUploadFile(file.filename);

            //异步 改成 同步
            await this.ctx.service.tools.uploadCos(filename, source);
        }
        await this.ctx.model.Product.create({
            ...body,
            ...{
                imgUrl: file ? filename : "",
                status: 1,
                addTime: this.ctx.service.tools.getUnixTime()
            }
        });
        await this.success("增加菜品成功", `/${this.config.adminPath}/product`);

    }

    async doUpload() {
        const { ctx } = this;
        const body = ctx.request.body;
        //文件信息
        const file = ctx.request.files[0];

        if (file) {
            var source = fs.createReadStream(file.filepath);
            var filename = this.ctx.service.tools.getCosUploadFile(file.filename);

            //异步 改成 同步
            await this.ctx.service.tools.uploadCos(filename, source);
        }

        ctx.body = { link: this.config.cosUrl + "/" + filename };
    }

    async edit() {
        let id = this.ctx.request.query.id;
        // console.log(this.ctx.state.prevPage);
        //获取所有分类        
        let cateResult = await this.ctx.model.ProductCate.findAll();

        //获取修改的数据
        let productResult = await this.ctx.model.Product.findAll({
            where: {
                id: id
            }
        })
        await this.ctx.render("admin/product/edit", {
            cateList: cateResult,
            product: productResult[0],
            prevPage:this.ctx.state.prevPage   //获取上一页的地址
        })
    }
    async doEdit() {
        const { ctx } = this;
        const body = ctx.request.body;
        const file = ctx.request.files[0];
        if (body.title == "") {
            await this.error("菜品名称不能为空", `/${this.config.adminPath}/product/edit?id=${body.id}`);
            return;
        }
        if (body.price == "") {
            await this.error("菜品价格不能为空", `/${this.config.adminPath}/product/edit?id=${body.id}`);
            return;
        }
        //获取要修改的数据
        let productObj = await this.ctx.model.Product.findByPk(body.id);
        if (!productObj) {
            await this.error("非法请求", `/${this.config.adminPath}/product/edit?id=${id}`);
            return;
        }

        if (file) {
            var source = fs.createReadStream(file.filepath);
            var filename = this.ctx.service.tools.getCosUploadFile(file.filename);
            //异步 改成 同步
            await this.ctx.service.tools.uploadCos(filename, source);
            await productObj.update({
                ...body,
                imgUrl:filename,
            });
        } else {
            await productObj.update(body);

        }
        let prevPage=body.prevPage?body.prevPage:`/${this.config.adminPath}/product`;

        await this.success("修改菜品成功",prevPage);

    }

    async delete() {
        try {
            let prevPage = this.ctx.state.prevPage;
            let id = this.ctx.request.query.id;
            let product = await this.ctx.model.Product.findByPk(id);
            if (!product) {
                await this.error("非法请求", `/${this.config.adminPath}/product`);
                return;
            }            
            //删除对象存储里面的图片
            if(product.imgUrl){
                await this.ctx.service.tools.deleteCos(product.imgUrl);
            }
            await product.destroy();
            await this.success("删除数据成功",prevPage);
        } catch (error) {
            await this.error("非法请求", `/${this.config.adminPath}/product`);
        }

    }


}

module.exports = ProductController;
